package ca.eloas.gpsclock.service;

import android.app.AlarmManager;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.HandlerThread;
import android.os.IBinder;
import android.widget.Toast;
import ca.eloas.gpsclock.Intents;
import ca.eloas.gpsclock.db.AlarmDatabase;
import ca.eloas.gpsclock.db.TimeAlarmInfo;

import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * User: jpbelang
 * Date: Sep 20, 2010
 * Time: 5:46:12 PM
 */
public class AlarmClockService extends Service {

    private AlarmChangeBroadcastReceiver receiver;
    private int nextAlarm;

    public class AlarmChangeBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {

            if ( intent.getAction().equals(Intents.CHANGED_ALARM )) {
            
                alarmChanged(intent.getLongExtra("id", 0));
                return;
            }

            if ( intent.getAction().equals(Intents.DELETED_ALARM )) {

                alarmDeleted(intent.getLongExtra("id", 0));
                return;
            }

        }
    }

    private void alarmChanged(long id) {
        
        TimeAlarm a = alarms.get(id);
        Toast.makeText(this, "Alarm " + a.getInfo().getId() + " changed", Toast.LENGTH_LONG).show();
    }

    private void alarmDeleted(long id) {

        TimeAlarm a = alarms.get(id);
        Toast.makeText(this, "Alarm " + a.getInfo().getId() + " deleted", Toast.LENGTH_LONG).show();
    }

    private AlarmDatabase database;
    private Map<Long, TimeAlarm> alarms = new HashMap<Long, TimeAlarm>();
    private AlarmManager alarmManager;

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        receiver = new AlarmChangeBroadcastReceiver();

        IntentFilter filter = new IntentFilter(Intents.CHANGED_ALARM);
        filter.addAction(Intents.DELETED_ALARM);
        registerReceiver(receiver, filter);




        database = new AlarmDatabase(this);
        alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        loadAllAlarms();
        return super.onStartCommand(intent, flags, startId);
    }

    
    private void findNextAlarm() {

        this.nextAlarm = Integer.MAX_VALUE;
        for (TimeAlarm timeAlarm : alarms.values()) {
            
            int secondsToNextOccurence = timeAlarm.nextOccurenceInSeconds();
            if ( secondsToNextOccurence < nextAlarm ) {

                nextAlarm = secondsToNextOccurence;
            }
        }

        if ( nextAlarm != Long.MAX_VALUE ) {

            Toast.makeText(this, "Next alarm in " + toHoursString(nextAlarm) + " minutes", Toast.LENGTH_LONG).show();
        }
    }

    private void loadAllAlarms() {
        
        List<TimeAlarmInfo> alarmlist = database.getAllAlarms();
        for (TimeAlarmInfo alarmInfo : alarmlist) {
        
            if ( alarmInfo.getActive() ) {

                TimeAlarm timeAlarm = new TimeAlarm(alarmInfo);
                timeAlarm.activate(alarmManager);
                alarms.put(alarmInfo.getId(), timeAlarm);

            } else {

                alarms.put(alarmInfo.getId(), new TimeAlarm(alarmInfo));
            }
        }

        findNextAlarm();
    }

    // todo do this with plurals and i18n
    private String toHoursString(long nextAlarm) {
        
        if ( nextAlarm < 3600 ) {
            
            return String.format("%d minutes", nextAlarm / 3600 );
        }
        
        if ( nextAlarm < 7200 ) {
            
            return String.format("1 hour and %d minutes", (nextAlarm % 3600) / 60);
        }
        
        
        return String.format("%d hours and %d minutes", nextAlarm / 3600, (nextAlarm % 3600) / 60 );
    }

    @Override
    public void onDestroy() {

        Toast.makeText(this, "TimeAlarm service stopped", Toast.LENGTH_SHORT).show();
    }

    @Override
    public IBinder onBind(Intent intent) {
        // We don't provide binding, so return null
        return null;
    }

}


